<template>
  <div>
    <!-- 添加申请表模板 -->
    <el-button
        class="addTemplate"
        type="primary"
        round
        @click="addTemplate"
        style="background-color: #803f7d; border-color: #000000;">
      <i class="el-icon-plus" style="margin-right: 3px;"></i>添加申请表模板
    </el-button>

    <!--字段库-->
    <el-button
        class="fieldLibrary"
        round
        @click="goToFieldLibrary">字段库</el-button>

    <!-- 搜索框 -->
    <el-input
        v-model="searchKeyword"
        placeholder="输入模板名称搜索"
        clearable
        style="width: 300px; float: right; margin-bottom: 20px;"
        @clear="fetchTemplateData"
        @keyup.enter.native="fetchTemplateData"
    >
      <el-button
          slot="append"
          icon="el-icon-search"
          @click="fetchTemplateData"
      />
    </el-input>

    <!-- 模板列表 -->
    <el-table
        :data="tableData"
        style="width: 100%"
        border
        v-loading="loading"
        :cell-style="{ borderRight: 'none' }"
        :header-cell-style="{ borderRight: 'none' }"
    >
      <el-table-column
          fixed
          prop="name"          
          label="模板名称"
      />
      <el-table-column
          prop="description"
          label="模板描述"
      />
      <el-table-column
          prop="createTime"
          label="创建时间"
      >
          <template slot-scope="scope">
              {{ formatTime(scope.row.createTime) }}
          </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
      >
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="primary"
              plain
              @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
              size="mini"
              type="danger"
              plain
              @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
// 引入 axios
import request from '@/utils/request'

export default {
  data() {
    return {
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 1,
      searchKeyword: '', // 添加搜索关键词
    };
  },
  methods: {
    async fetchTemplateData() {
      this.loading = true;
      try {
        const res = await request.get('/admin/templates/list');
        
        if (res && res.code === 1) {
          // 添加详细的数据检查
          console.log('数据详情:', JSON.stringify(res.data[0], null, 2));
          
          this.tableData = Array.isArray(res.data) ? res.data.map(item => ({
            ...item,
            name: item.templateName // 确保name字段与templateName保持一致
          })) : [];
          
          console.log('处理后的第一条数据:', JSON.stringify(this.tableData[0], null, 2));
          this.total = this.tableData.length;
        } else {
          this.$message.error(res?.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('请求失败:', error);
        this.$message.error('获取数据失败：' + (error?.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    async handleEdit(row) {
      try {
        const res = await request.get(`/admin/formtemplate/detail/${row.id}`);
        console.log('数据详情:', res.data);
        
        if (res && res.code === 1) {
          // 使用 fieldGroup 作为适用人群信息
          this.$router.push({
            path: '/main/template/addTemplate',
            query: { 
              id: row.id,
              applicantGroup: res.data.fieldGroup || row.fieldGroup // 优先使用详情数据中的 fieldGroup
            }
          });
        } else {
          this.$message.error(res?.msg || '获取模板详情失败');
        }
      } catch (error) {
        console.error('获取模板详情失败:', error);
        this.$message.error('获取模板详情失败：' + (error?.message || '未知错误'));
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该模板及其所有关联字段配置, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const res = await request.delete(`/admin/formtemplate/delete/${row.id}`);
        
        if (res && res.code === 1) {
          this.$message.success('删除成功');
          this.fetchTemplateData(); // 刷新列表
        } else {
          this.$message.error(res?.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') { // 排除用户取消的情况
          console.error('删除失败:', error);
          this.$message.error('删除失败：' + (error?.message || '未知错误'));
        }
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchTemplateData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchTemplateData();
    },
    addTemplate() {
      // 跳转到添加模板页面
      this.$router.push('/main/template/addTemplate');
    },
    
    goToFieldLibrary() {
      // 跳转到字段库页面
      this.$router.push('/main/template/fieldLibrary');
    },
    formatTime(time) {
        if (!time) return '';
        return new Date(time).toLocaleString();
    }
},
mounted() {
    console.log('TemplatePage 组件已挂载');
    this.fetchTemplateData();
},

created() {
    console.log('TemplatePage 组件已创建');
}}
</script>
<style>
.addTemplate {
  margin-bottom: 20px;
  float: left;
}

.fieldLibrary {
  position: relative;
  left: 350px;
}

/* 调整表格样式 */
.el-table {
  font-size: 14px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 调整表格行高 */
.el-table ::v-deep .el-table__row td {
  padding: 8px 0;
}
</style>
